package com.xkdx.guangguang.fragment.shop;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xkdx.caipiao.HomePageActivity;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ShopActivity;
import com.xkdx.guangguang.WebViewShowActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.map.ShopMapFragment;
import com.xkdx.guangguang.fragment.shop.search.SearchShopFragment;
import com.xkdx.guangguang.fragment.shopinfo.ShopInfoFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.Shop;
import com.xkdx.guangguang.util.SharePrefenceUtil;
import com.xkdx.guangguang.wiget.XListView;
import com.xkdx.guangguang.wiget.XListView.IXListViewListener;

public class ShopFragment extends BaseFragment implements OnGestureListener,
		OnTouchListener, OnClickListener, IXListViewListener {
	View view, viewflipper_view;
	ImageLoader imageLoader = ImageLoader.getInstance();
	ShopPersisenter persisenter;
	DisplayImageOptions options;
	ImageView search, map, back;
	TextView tv_shopCurrentPosition;
	XListView listView;
	ViewFlipper viewFlipper;
	Drawable[] viewFlipperDrawables;
	String currentPosition;
	GestureDetector detector;
	String[] shopInfoID = { "103351", "95", "95582" };
	ShopAction shopAction;
	ShopModule shopModule;
	LocationManager locationManager;

	// 图片轮播
	ShopPicPersisenter picPersisenter;
	ShopPicAction mShopPicAction;
	ShopPicModule mShopPicModule;
	List<ImageView> dots;
	List<String> picUrls;
	List<String> webUrls;
	List<String> titleList;
	LinearLayout dotsContainer;

	ShopListAdapter adapter;
	List<Shop> shopList;
	int currentPointNum = 0;
	int width = 0;
	float scale;
	boolean isRunning = true;
	String cityID;
	String lat, lon;
	int PageIndex = 1;
	public static boolean isLoadMore = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.focuse_brand_discount)
				.showImageForEmptyUri(R.drawable.focuse_brand_discount)
				.showImageOnFail(R.drawable.focuse_brand_discount)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		width = dm.widthPixels;
		scale = getActivity().getResources().getDisplayMetrics().density;
		dots = new ArrayList<ImageView>();
		picUrls = new ArrayList<String>();
		webUrls = new ArrayList<String>();
		titleList = new ArrayList<String>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.shop, container, false);
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		IConstants.hideInputMethodAways(getActivity(), view);
		viewFlipperDrawables = new Drawable[] {
				getResources()
						.getDrawable(R.drawable.shop_viewflipper_laifushi),
				getResources().getDrawable(
						R.drawable.shop_viewflipper_weilaiguangchang) };
		detector = new GestureDetector(this);
		map = (ImageView) view.findViewById(R.id.shop_showMap_btn);
		search = (ImageView) view.findViewById(R.id.shop_search_btn);
		back = (ImageView) view.findViewById(R.id.shop_back);
		back.setOnClickListener(this);
		listView = (XListView) view.findViewById(R.id.strollshop_list);
		tv_shopCurrentPosition = (TextView) view
				.findViewById(R.id.shop_current_position_tv);
		listView.removeFooter();
		listView.setPullLoadEnable(true);
		viewflipper_view = LayoutInflater.from(getActivity()).inflate(
				R.layout.shop_viewflipper, null);
		viewFlipper = (ViewFlipper) viewflipper_view
				.findViewById(R.id.shop_focuse_im);
		viewFlipper.setOnTouchListener(touchListener);
		viewFlipper.setLongClickable(true);

	}

	@Override
	public void setOnClick() {
		map.setOnClickListener(this);
		search.setOnClickListener(this);
		listView.setXListViewListener(this);
	}

	@Override
	public void showLoading() {

		PageIndex = 1;
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
				IConstants.SP_CITY);
		String cityID = "";
		if (IConstants.isChoiceCity) {
			cityID = su.getCityID();
		} else {
			String cityName = su.getLocationCityName().substring(0,2);
			if (HomePageActivity.cityList != null
					&& HomePageActivity.cityList.size() > 0) {
				for(Map<String, String> cityMap:HomePageActivity.cityList){
					Iterator<Entry<String, String>> iterator = cityMap.entrySet().iterator();
					Entry<String, String> idEntry = iterator.next();
					String itemID = idEntry.getValue();
					Entry<String, String> nameEntry = iterator.next();
					String itemCityName = nameEntry.getValue().substring(0, 2);
					if(cityName.equals(itemCityName)){
						cityID = itemID;
						su.setCityID(cityID);
						IConstants.isChoiceCity = true;
						break;
					}
				}
			}
		}

		persisenter = new ShopPersisenter(this);
		shopAction = new ShopAction(cityID, String.valueOf(IConstants.lon),
				String.valueOf(IConstants.lat), "-1");
		shopModule = new ShopModule();
		persisenter.setActitons(shopAction);
		persisenter.setModule(shopModule);
		persisenter.execute();

		mShopPicAction = new ShopPicAction();
		mShopPicModule = new ShopPicModule();
		mShopPicModule.setUrls(picUrls);
		mShopPicModule.setTitleList(titleList);
		mShopPicModule.setWebUrlList(webUrls);
		picPersisenter = new ShopPicPersisenter(this);
		picPersisenter.setActitons(mShopPicAction);
		picPersisenter.setModule(mShopPicModule);
		picPersisenter.execute();

		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (persisenter != null) {
					persisenter.cancel(true);
				}
				getActivity().finish();
			}
		});
		if (getActivity() != null) {
			dataLoadDialog.show();
		}
	}

	public void updatePic() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> msg) {
		if (getActivity() == null) {
			return;
		}
		dataLoadDialog.dismiss();
		if (msg.containsKey("0")) {
			if (IConstants.lat == 0) {
				refreshShop();
			} else {
				shopList = shopModule.list;
				setListAdapter();
				tv_shopCurrentPosition.setText(IConstants.currentPosition);
				((ShopActivity) getActivity()).setShopHomeList(shopList);
			}
		} else {
			refresh(msg);
		}
		onLoad();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shop_search_btn:
			SearchShopFragment searchShopFragment = new SearchShopFragment();
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, searchShopFragment)
					.addToBackStack(null).commit();
			break;
		case R.id.shop_showMap_btn:
			ShopMapFragment shopMapFragment = new ShopMapFragment();
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, shopMapFragment)
					.addToBackStack(null).commit();

			break;
		case R.id.shop_back:
			getActivity().finish();
			break;
		default:
			break;
		}

	}

	OnTouchListener touchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			return detector.onTouchEvent(event);
		}
	};

	protected void setListAdapter() {
		adapter = new ShopListAdapter(getActivity(), shopList);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position != 1) {
					ShopInfoFragment shopInfoFagment = new ShopInfoFragment();
					Bundle b = new Bundle();
					b.putString("shopID", shopList.get(position - 2)
							.getShopID());
					shopInfoFagment.setArguments(b);
					getFragmentManager().beginTransaction()
							.replace(R.id.fragment, shopInfoFagment)
							.addToBackStack(null).commit();
				}
			}

		});

	}

	class ShopListAdapter extends BaseAdapter {

		String url;
		Context context;
		List<Shop> list;
		LayoutInflater inflater;
		int height;

		public ShopListAdapter(Context context, List<Shop> list) {
			super();
			this.list = list;
			this.context = context;
			inflater = LayoutInflater.from(context);

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size() + 1;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if (position == 0) {
				return null;
			} else {
				return list.get(position - 1);
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ImageView im = null, image = null;
			ImageView iv_shop1 = null, iv_shop2 = null, iv_shop3 = null;// zshun增加图标显示
			TextView name = null, distance = null, shop_address = null;

			int type = getItemViewType(position);
			switch (type) {
			case 1:
				viewFlipper.removeAllViews();
				dotsContainer = (LinearLayout) viewflipper_view
						.findViewById(R.id.llayout);
				dotsContainer.removeAllViews();
				dots.clear();
				for (int i = 0; i < picUrls.size(); i++) {
					ImageView dotImageView = new ImageView(getActivity());
					dotImageView.setImageResource(R.drawable.guide_round);
					dotImageView.setPadding(6, 6, 0, 0);
					dots.add(dotImageView);
					dotsContainer.addView(dotImageView);
				}
				setEnable(currentPointNum);
				for (int i = currentPointNum; i < picUrls.size(); i++) {
					View photo_view = inflater.inflate(
							R.layout.shop_home_viewflipper, null);
					ImageView iv = (ImageView) photo_view
							.findViewById(R.id.shop_home_viewflipper_iv);
					imageLoader.displayImage(picUrls.get(i), iv, options);
					viewFlipper.addView(photo_view);
				}
				// for (int i = 0; i < currentPointNum; i++) {
				// View photo_view = inflater.inflate(
				// R.layout.shop_home_viewflipper, null);
				// ImageView iv = (ImageView) photo_view
				// .findViewById(R.id.shop_home_viewflipper_iv);
				// iv.setImageDrawable(viewFlipperDrawables[i]);
				// viewFlipper.addView(photo_view);
				// }
				view = viewflipper_view;
				break;
			case 2:
				view = inflater.inflate(R.layout.shop_item, null);
				image = (ImageView) view.findViewById(R.id.series_item_image);
				distance = (TextView) view.findViewById(R.id.distandce);
				name = (TextView) view.findViewById(R.id.name);
				shop_address = (TextView) view.findViewById(R.id.shop_address);
				iv_shop1 = (ImageView) view.findViewById(R.id.iv_shop1);
				iv_shop2 = (ImageView) view.findViewById(R.id.iv_shop2);
				iv_shop3 = (ImageView) view.findViewById(R.id.iv_shop3);
				break;

			}

			switch (type) {
			case 1:
				break;
			case 2:
				name.setText(list.get(position - 1).getShopName());
				int num = 0;
				if (list.get(position - 1).getIcon() != null
						&& list.get(position - 1).getIcon().size() > 0) {
					num = list.get(position - 1).getIcon().size();
				}

				ComputeMaxLength(num, name, iv_shop1);

				if (!"False".equals(list.get(position - 1).getIcon1())) {
					iv_shop1.setVisibility(View.VISIBLE);
					iv_shop1.setImageResource(R.drawable.shop_guan_v);
				} else {
					iv_shop1.setVisibility(View.GONE);
				}
				if (!"False".equals(list.get(position - 1).getIcon2())) {
					iv_shop2.setVisibility(View.VISIBLE);
					iv_shop2.setImageResource(R.drawable.shop_hui_v);
				} else {
					iv_shop2.setVisibility(View.GONE);
				}
				if (!"False".equals(list.get(position - 1).getIcon3())) {
					iv_shop3.setVisibility(View.VISIBLE);
					iv_shop3.setImageResource(R.drawable.shop_zhe_v);
				} else {
					iv_shop3.setVisibility(View.GONE);
				}

				shop_address.setText(list.get(position - 1).getAddress());
				if (list.get(position - 1).getDistance() != null) {
					String distance1 = list.get(position - 1).getDistance();
					double dis;
					try {
						dis = Double.parseDouble(distance1) / 1000;
					} catch (Exception e) {
						dis = 0;
					}

					if (dis > 1) {
						DecimalFormat df = new DecimalFormat("#.0");
						String format = df.format(dis);
						distance.setText(format
								+ getResources().getString(R.string.kilometer));
					} else if (dis > 0 && dis < 1) {
						distance.setText(distance1
								+ getResources().getString(R.string.meter));
					} else if (dis <= 0) {
						distance.setText(getResources().getString(
								R.string.unknown));
					}

				}

				url = list.get(position - 1).getLogo();
				if (url != null) {
					imageLoader.displayImage(url, image, options);
				}

				break;
			}

			return view;

		}

		@Override
		public int getItemViewType(int position) {
			switch (position) {
			case 0:
				return 1;
			default:
				return 2;
			}
		}

	}

	private void setEnable(int currentPointNum) {

		if (currentPointNum >= 0 && currentPointNum < picUrls.size()) {
			for (int i = 0; i < picUrls.size(); i++) {
				dots.get(i).setEnabled(i != currentPointNum);
			}
		}

		switch (currentPointNum) {

		case 0:
			// Log.i(TAG, "0-->");
			// point1.setEnabled(false);
			// point2.setEnabled(true);
			// point3.setEnabled(true);
			break;
		case 1:
			// Log.i(TAG, "1-->");
			// point1.setEnabled(true);
			// point2.setEnabled(false);
			// point3.setEnabled(true);
			break;
		case 2:
			// Log.i(TAG, "2-->");
			// point1.setEnabled(true);
			// point2.setEnabled(true);
			// point3.setEnabled(false);
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public void ComputeMaxLength(int num, TextView name, ImageView iv_shop1) {
		int maxpixels = 0;
		int w_width = 0;
		if (num > 0) {
			LayoutParams lp = iv_shop1.getLayoutParams();
			w_width = (lp.width) * num;
		}
		int margin_width = 2 * num;
		maxpixels = width - dip2px(69 + margin_width + 25 + 12 + 30, scale)
				- w_width;
		name.setMaxWidth(maxpixels);

	}

	/**
	 * 将dip或dp值转换为px值，保证尺寸大小不变
	 * 
	 * @param scale
	 *            （DisplayMetrics类中属性density）
	 * @return
	 */
	public static int dip2px(float dipValue, float scale) {
		return (int) (dipValue * scale + 0.5f);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > 100) {
			viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.left_in));
			viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.left_out));
			currentPointNum++;
			if (currentPointNum > picUrls.size() - 1) {
				currentPointNum = 0;
			}
			viewFlipper.showNext();
			setEnable(currentPointNum);
			return true;

		} else if ((e1.getX() - e2.getX() < -100)) {
			viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.right_in));
			viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.right_out));
			currentPointNum--;
			if (currentPointNum < 0) {
				currentPointNum = picUrls.size() - 1;
			}
			viewFlipper.showPrevious();
			setEnable(currentPointNum);
			return true;
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub

		return true;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		/*
		 * if (currentPointNum == 0) { Intent intent = new Intent(getActivity(),
		 * BhgActivity.class); startActivity(intent); } else {
		 * FragmentTransaction ft = getFragmentManager().beginTransaction();
		 * ShopInfoFragment shopInfoFragment = new ShopInfoFragment(); Bundle b
		 * = new Bundle(); b.putString("shopID", shopInfoID[currentPointNum]);
		 * shopInfoFragment.setArguments(b); ft.replace(R.id.fragment,
		 * shopInfoFragment); ft.addToBackStack(null); ft.commit();
		 * 
		 * }
		 */
		
		if (webUrls.size() >currentPointNum && !TextUtils.isEmpty(webUrls.get(currentPointNum))) {
			Intent intent = new Intent(getActivity(), WebViewShowActivity.class);
			Bundle b = new Bundle();
			b.putString(WebViewShowActivity.URL, webUrls.get(currentPointNum));
//			b.putString(WebViewShowActivity.TITLE, titleList.get(currentPointNum));
			intent.putExtras(b);
			startActivity(intent);
		}
		return false;
	}

	@Override
	public void onRefresh() {
		showLoading();
	}

	@Override
	public void onLoadMore() {
		if (!isLoadMore) {
			isLoadMore = true;
			PageIndex++;
			shopAction.pageIndex = PageIndex;
			persisenter = new ShopPersisenter(this);
			persisenter.setActitons(shopAction);
			persisenter.setModule(shopModule);
			persisenter.execute();
		}
	}

	@Override
	public void showClick(HashMap<String, AbsModule> msg) {

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> msg) {
		isLoadMore = false;
		if (msg.containsKey("0")) {
			List<Shop> addList = ((ShopModule) msg.get("0")).list;
			for (Shop shop : addList) {
				shopList.add(shop);
			}
			((ShopActivity) getActivity()).setShopHomeList(shopList);
			adapter.notifyDataSetChanged();
			onLoad();
		} else {
			refresh(msg);
		}

	}

	private void onLoad() {
		listView.stopRefresh();
		listView.stopLoadMore();
		listView.setRefreshTime(getCurrentTime());
	}

	private String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("MM-dd hh:mm");
		Date date = new Date(System.currentTimeMillis());
		return format.format(date);
	}
}
